//app.js
// let url = '://it.sucheon.com'
let url = '://product.sucheon.com'
function createSocket() {
  return wx.connectSocket({
    url: `wss${url}/websocket/message`,
  });
}


let socketMsgQueue = []
App({
  socketEvents: {},
  onShow: function (options) {
    var it = this;
    it.initSocket();
  },
  onLaunch(){
    if (wx.getStorageSync('token')) {
      wx.reLaunch({
        url: '/pages/totalMsg/totalMsg',
        // url: '/pages/deviceDetail/deviceDetail',
      })
    }
    wx.setStorageSync('canRequest', true)
    
  },
  initSocket: function () {
    var it = this;
    it.socketTask = createSocket();

    it.socketTask.onOpen(function (res) {
      console.log('已连接WebSocket！可以传输数据！')
      it.globalData.isOpen = true
    });
    //非正常关闭socket后，重连
    it.socketTask.onClose(function (res) {
      console.log('已关闭socket')
      if (res.code === 1000) {
        return;
      }
      setTimeout(function () {
        console.log('重连')
        it.initSocket();
      }, 1000);
    });
    // 注册消息回调事件
    it.socketTask.onMessage(function (res) {
      it.globalData.callback(res)
    });
  },
  closeSocket: function () {
    if (this.socketTask) {
      this.socketTask.close();
    }
  },
  onHide: function () {
    this.closeSocket();
    this.globalData.isOpen = false
  },
  openSendMsg(msg) {
    socketMsgQueue.push(msg)
    while (socketMsgQueue.length > 0) {
      var msg = socketMsgQueue.shift();
      this.socketTask.send({
        data: JSON.stringify(msg)
      })
    }
  },
  // 全局监听全局参数
  watch: function (val, fn = () => { }) {
    Object.defineProperty(this.globalData, val, {
      configurable: true,
      enumerable: true,
      set: function (value) {
        this['_' + val] = value
        fn(value)
      },
      get: function () {
        return this['_' + val]
      }
    })
  },
  globalData: {
    userInfo: null,
    requestBool: false, // 防止重复请求
    deviceName: {},
    deviceList: [],
    multiList: [],
    multiArray: [],
    pickerIndex: [],
    result: [], // 原始树形数据
    url: url,
    localSocket: {},
    callback: function () { },
    isOpen: false,
    tokenError: false,
    structureData: null,
    curStructure: null,
    timer: null,
    isState: true,
    deatilNav: [], // 总览上面的面包屑
    deatilList: [], // 总览数据
    showNav: true, // 展示树形面板
    mostStatus: '', // 厦门卷烟厂 状态字段 出现最多次
    deviceList: '', // 设备数组集合
    showPicker: false,
    treeInfo: '',// 整机维保左侧设备
    deviceID: '',
  },

})